<?php

namespace app\shop\model\settings;

use app\common\model\settings\Shoptime as ShoptimeModel;
use app\common\model\settings\Region as RegionModel;
use app\common\model\supplier\Supplier;
use think\facade\Db;

/**
 * 营业时间模型
 */
class Shoptime extends ShoptimeModel
{
	/**
	 * 获取列表
	 */
	public function getList($where)
	{
		$model = $this->with(['supplier']);
		if($where['search']){
			$searchname = $where['search'];
			$supplierid = (new supplier)->where('name','=',$searchname)->value('shop_supplier_id');
			$model = $model->where('time_range','=',1)->where('shop_supplier_id','=',$supplierid);
		}
		if($where['province_id']||$where['city_id']){
			$province_id = $where['province_id'];
			$city_id = $where['city_id'];
			if($city_id){
				$suppliers = (new supplier)->where('city_id','=',$city_id)->where('is_delete','=',0)->column('shop_supplier_id');
				$regionids = $city_id;
			}else{
				$suppliers = (new supplier)->where('province_id','=',$province_id)->where('is_delete','=',0)->column('shop_supplier_id');
				$regionids = RegionModel::withoutGlobalScope()->where('id','=',$province_id)->whereOr('pid','=',$province_id)->column('id');
			}
			$model = $model->where(function($query) use ($regionids,$suppliers){
				$query->where(function($query) use ($regionids){
					$query->where('time_range','=',0)->where('area_id','in',$regionids);
				})
				->whereOr(function($query) use ($suppliers){
					$query->where('time_range','=',1)->where('shop_supplier_id','in',$suppliers);
				});
			});
		}
		$list = $model->order(['sort' => 'asc'])
			->paginate($where)
			->each(function($item, $key){
				$relabel = '全国';
				$revaid = 0;
				$regionrs = RegionModel::withoutGlobalScope()->where('id','=',$item['area_id'])->find();
				if($regionrs){
					$revaid = $regionrs['id'];
					$relabel = $regionrs['name'];
				}
				$regionary = ['id'=>$revaid,'label'=>$relabel];
				$item->region = $regionary;
			});
		return $list;
	}

}